import pandas as pd
import socket
import datetime
import json


def LogTaskAndMachine(tableName, engine, conn, executeAccount='', runMode=''):
    hostname = socket.gethostname()
    machineDes = ''
    sqlLoop = "SELECT * FROM 平台_物理机虚拟机 where 机器名称='" + hostname + "' "
    dfLoop = pd.read_sql(sql=sqlLoop, con=engine)
    for index, row in dfLoop.iterrows():
        machineDes = row['机器描述']

    sqlTask = ' select * from 平台_任务_机器_实例表 where 1=2 '
    df = pd.read_sql(sql=sqlTask, con=engine)

    jsonObj = [{"任务表名称": tableName, "当前运行机器名": hostname, "运行机器描述": machineDes,
                "开始运行时间": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "执行账号": executeAccount,
                "运行模式": runMode}]
    df = pd.read_json(json.dumps(jsonObj))
    # 解决可能出现的超时问题bugfix 2020.08.18
    conn.connection.connection.ping(reconnect=True)
    df.to_sql(name='平台_任务_机器_实例表', con=conn, if_exists='append', index=False)

    return


def LogContinueException(tableName, engine, conn, exceptionMsg, runMode):
    hostname = socket.gethostname()
    machineDes = ''
    sqlLoop = "SELECT * FROM 平台_物理机虚拟机 where 机器名称='" + hostname + "' "
    dfLoop = pd.read_sql(sql=sqlLoop, con=engine)
    for index, row in dfLoop.iterrows():
        machineDes = row['机器描述']

    sqlTask = ' select * from 平台_任务_机器_实例表 where 1=2 '
    df = pd.read_sql(sql=sqlTask, con=engine)

    jsonObj = [{"任务表名称": tableName, "当前运行机器名": hostname, "运行机器描述": machineDes,
                "开始运行时间": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "异常描述": exceptionMsg, "运行模式": runMode}]
    df = pd.read_json(json.dumps(jsonObj))
    # 解决可能出现的超时问题bugfix 2020.08.18
    conn.connection.connection.ping(reconnect=True)
    df.to_sql(name='平台_任务异常信息', con=conn, if_exists='append', index=False)

    return
